//
//  MainViewController.swift
//  Residual_mem
//
//  Created by 武振磊 on 16/7/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    //MARK: 监听方法
    @objc private func clickComposedButton() {
        print("点我了")
    }

    //MARK: 视图生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
//          添加控制器并不会创建TabBar中的按钮
//          懒加载是无处不在的，所有的控件都是延迟创建的。
        addChildViewControllers()
        addComposedButton()
    }
    
    override func viewWillAppear(animated: Bool) {
        //会创建TabBar中所有控制器的按钮
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composedButton)
    }
    
//MARK: 懒加载撰写按钮
    private lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
}

//MARK:  设置界面
extension MainViewController{
    
///   添加撰写按钮
    private func addComposedButton(){
        
        tabBar.addSubview(composedButton)
        let count = childViewControllers.count
        //让按钮宽一点点，能够解决手指触摸的容错问题
        let Width = UIScreen.mainScreen().bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds, Width * 2, 0)
        
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
    }
///   添加所有的自控制器
    private func addChildViewControllers() {
        
        //一次性设置Tabbar的颜色，避免使用图片，提高性能
        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoveryTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }

    ///   添加控制器
    ///
    ///   - parameter vc:        vc
    ///   - parameter title:     title
    ///   - parameter imageName: imageName
    private func addChildViewController(vc:UIViewController, title:String, imageName:String
        ) {
        
        //标题设置由内而外依次设置
        vc.title = title
        //设置图像
        vc.tabBarItem.image = UIImage(named: imageName)
        //导航控制器
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }
}